﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Utility;
using Common.Unity.Extensions;

namespace Common.Unity
{
	public class UnityContainerTypeConverter<TargetType> : TypeConverter
	{
		readonly IUnityContainer container;

		public UnityContainerTypeConverter( IUnityContainer container )
		{
			Guard.ArgumentNotNull( container, "container" );
			this.container = container;
		}

		public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
		{
			return true;
		}

		public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
		{
			return true;
		}

		public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
		{
			var result = container.Resolve( typeof(TargetType), null, value );
			return result;
		}

		public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
		{
			var result = container.Resolve( destinationType, null, value );
			return result;
		}
	}
}
